package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.UserNotLoginException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Slf4j
public class OrderServicelmpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;
    /**
     * 完成用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 1:封装Orders 数据 存到数据库 orders
        Orders orders = new Orders();
        // 1.1 把 dto数据 拷贝到 orders中
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        // 1.2  基本信息 订单号
        // 时间毫秒值 当成订单号  uuid  雪花算法
        orders.setNumber(System.currentTimeMillis()+"");
        // 订单状态
        orders.setStatus(Orders.PENDING_PAYMENT);
        // 用户id
        Long userId = BaseContext.getCurrentId();
        orders.setUserId(userId);
        // 下单时间
        orders.setOrderTime(LocalDateTime.now());
        //支付状态
        orders.setPayStatus(Orders.UN_PAID);
        // 1.3 地址信息  phone address consignee 信息来自于地址薄
        // 根据地址id 去地址簿查询
        Long addressBookId = orders.getAddressBookId();
        // 去地址簿查
        AddressBook addressBook = addressBookMapper.getById(addressBookId);
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setAddress(addressBook.getDetail());
        // 封装之后 存到数据库
        orderMapper.insert(orders);

        // 2:封装OrderDetail 数据 存到数据库 order_detail
        // 先去查询 当前用户的 所有购物项--购物车数据  购物车数据转换成订单详情
        ShoppingCart shoppingCart = new ShoppingCart();
        //封装查询条件
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.list(shoppingCart);
        //你可以自己做个判断 购物为空 抛出异常
        if (shoppingCarts == null){
           throw new UserNotLoginException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 订单明细是多个---购物项  一个订单明细 对应一个 购物项
        List<OrderDetail> orderDetailList = new ArrayList<>();
        //遍历一个购物项  生成一个 订单名单
        // 搞一个订单明细 存一个订单明细
        for (ShoppingCart cart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail,"id");//排除掉id
            orderDetail.setOrderId(orders.getId());
            //存到集合中
            orderDetailList.add(orderDetail);
        }
        // 最终 加到 订单明细表中
        orderDetailMapper.insertBatch(orderDetailList);
        // 3: 清空购物车
        shoppingCartMapper.delete(BaseContext.getCurrentId());
        // 4: 封装返回结果
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        //订单id
        orderSubmitVO.setId(orders.getId());
        //订单支付价格
        orderSubmitVO.setOrderAmount(orders.getAmount());
        //订单号
        orderSubmitVO.setOrderNumber(orders.getNumber());
        //下单时间
        orderSubmitVO.setOrderTime(orders.getOrderTime());

        Map map =new HashMap<>();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","订单号："+orders.getNumber());
        //把map转换为josn格式
        String message = JSON.toJSONString(map);
        log.info("查看格式：{}",message);
        webSocketServer.sendToAllClient(message);


        return orderSubmitVO;

    }
    //   历史订单查询
    @Override
    public PageResult pageQuery(int page, int pageSize, Integer status) {

        //设计页数
        PageHelper.startPage(page,pageSize);
        //开始分页查询
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        //所查的id为用户的id
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);
        //分页查询的条件
        Page<Orders> p = orderMapper.pageOrders(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList<>();
        //进行判断
        if (p != null&& p.getTotal()>0){
            //查询出订单明细，并封装入OrderVO进行响应
            for (Orders orders : p) {
                Long orderId = orders.getId();

                //查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
                //进行封装
                OrderVO orderVO = new OrderVO();
                //把值拷贝到orderVO
                BeanUtils.copyProperties(orders,orderVO);
                orderVO.setOrderDetailList(orderDetails);
                //添加到集合中
                list.add(orderVO);

            }

        }

        return new PageResult(p.getTotal(),list);
    }

    @Override
    public OrderVO details(Long id) {
        //根据id查询
        Orders orders = orderMapper.getById(id);
        //查询该订单对应的菜品
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
        //将订单封装到OrderVO返回
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);

        orderVO.setOrderDetailList(orderDetailList);


        return orderVO;
    }

    //取消订单
    @Override
    public void userById(Long id) {
        //根据id查询订单
        Orders ordersId = orderMapper.getById(id);
        //对其进行判断，没有的话抛异常
        if(ordersId == null){
            throw  new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (ordersId.getStatus() >2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersId.getId());

        //订单处于接单状态下取消
        if(ordersId.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            log.info("由于未申请商家这里暂时 演示一下即可 不用真实操作");

            orders.setPayStatus(Orders.REFUND);
        }
        //更新状态
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    //再来一单
    @Override
    public void reprtition(Long id) {
        //查询当前用户的Id
        Long userId = BaseContext.getCurrentId();
        //根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        //将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = new ArrayList<>();

        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            //将原订单详情的菜品信息复制到购物车对象中
            BeanUtils.copyProperties(orderDetail,shoppingCart,"id");
            shoppingCart.setUserId(userId);
            //设计时间为当前时间
            shoppingCart.setCreateTime(LocalDateTime.now());
            //将数据添加到集合中
            shoppingCartList.add(shoppingCart);

            shoppingCartMapper.insertBatch(shoppingCartList);
        }
    }
/*
管理端的订单搜索
 */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);
        // 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
        //设置一个集合用来存储
        List<OrderVO> list = new ArrayList<>();
            //进行遍历
        for (Orders orders : page) {
            //获取他的id
            Long id = orders.getId();
                //根据id进行查询
            List<OrderDetail> detailList = orderDetailMapper.getByOrderId(id);
            StringBuilder sb = new StringBuilder();
                //对其进行遍历
            for (OrderDetail orderDetail : detailList) {
                String name = orderDetail.getName();
                Integer number = orderDetail.getNumber();
                //进行拼接
                sb.append(name).append("*").append(number).append(";");
            }


            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders,orderVO);
            //进行赋值
            orderVO.setOrderDishes(sb.toString());
            //添加到集合中
            list.add(orderVO);
        }

        return new PageResult(page.getTotal(),list);

    }

    @Override
    public OrderStatisticsVO statistics() {

        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed =orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();

        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);

        return orderStatisticsVO;
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
//        Orders orders = Orders.builder()
//                .id(ordersConfirmDTO.getId())
//                .status(Orders.CONFIRMED)
//                .build();
        Orders orders = new Orders();
        orders.setId(ordersConfirmDTO.getId());
        orders.setStatus(ordersConfirmDTO.getStatus());

        orderMapper.update(orders);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersRejectionDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == Orders.PAID) {
            //用户已支付，需要退款 ---
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
            log.info("假设申请了退款");
        }

        // 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(ordersCancelDTO.getId());

        //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == 1) {
            //用户已支付，需要退款
//            String refund = weChatPayUtil.refund(
//                    ordersDB.getNumber(),
//                    ordersDB.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            log.info("申请退款：{}", refund);
            log.info("暂时未实现支付 所以退款为测试内容..已完成退款");
        }

        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    @Override
    public void delivery(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(orders);
    }

    @Override
    public void complete(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为完成
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());

        orderMapper.update(orders);
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO)throws Exception{
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    //用户催单
    @Override
    public void remider(Long id) {
        Orders orders = orderMapper.getById(id);

        if (orders==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //基于websocket
        Map map = new HashMap();
        map.put("type",2);
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
                                        //转换为josn格式
        webSocketServer.sendToAllClient(JSON.toJSONString(map));;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param orderNumber
     */
    public void paySuccess(String orderNumber) {
        log.info("支付完成 orderNumber:{}",orderNumber);
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(orderNumber, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }


}
